package main

import (
	"fmt"
	"os"
	"path/filepath"

	"github.com/astaxie/beego/logs"
	"github.com/kardianos/service"
	"github.com/robfig/cron"
)

func init() {
	logPath, _ := filepath.Abs(filepath.Dir(os.Args[0]))
	logPath = filepath.ToSlash(logPath)
	config := fmt.Sprintf(`{"filename":"%s/logs/xxx.log","level":7,"maxlines":0,"maxsize":0,"daily":true,"maxdays":10,"color":true}`, logPath)
	logs.SetLogger(logs.AdapterConsole, `{"level":7,"color":true}`)
	//logs.SetLogger(logs.AdapterFile, `{"filename":"logs/xxx.log","level":7,"maxlines":0,"maxsize":0,"daily":true,"maxdays":10,"color":true}`)
	logs.SetLogger(logs.AdapterFile, config)
	logs.SetLogFuncCall(true)
}

var (
	logger service.Logger
)

type program struct{}

// Start()
func (p *program) Start(s service.Service) error {
	// Start should not block. Do the actual work async.
	go p.run()
	logs.Info("service start...")
	return nil
}
func (p *program) run() {
	// Do work here
	logs.Info("service running...")
	cron := cron.New()
	cron.AddFunc("*/1 * * * * *", func() { logs.Info("log message") })
	//cron.Start()
	cron.Run()
	defer cron.Stop()
}

// Stop()
func (p *program) Stop(s service.Service) error {
	// Stop should not block. Return with a few seconds.
	logs.Info("service stop...")
	return nil
}

func main() {
	svcConfig := &service.Config{
		Name:        "GoServiceName",
		DisplayName: "GoServiceDisplayName",
		Description: "GoServiceDescription",
	}

	prg := &program{}
	s, err := service.New(prg, svcConfig)
	if err != nil {
		logs.Error(err)
		os.Exit(1)
	}
	logger, err = s.Logger(nil)
	if err != nil {
		logs.Error(err)
		os.Exit(1)
	}

	//
	if len(os.Args) > 1 {
		logs.Info("service control command: ", os.Args[1])
		err = service.Control(s, os.Args[1])
		if err != nil {
			logs.Error(err)
			os.Exit(1)
		}
		logs.Info("service %s control success", os.Args[1])
		return
	}

	//
	err = s.Run()
	if err != nil {
		logger.Error(err)
		logs.Error(err)
	}
}
